// 1. React核心库
import React, { useState, useRef } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Space, Tag, Tooltip, Popconfirm, Modal, Form, Input, Switch } from 'antd';

// 3. 图标库
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  ReloadOutlined,
  KeyOutlined,
  TeamOutlined,
  EyeOutlined
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import { history } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { RoleList, RoleRequest, RoleStatusRequest } from '@/services/generated/src/index';

const RolesPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [toggleLoading, setToggleLoading] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentRole, setCurrentRole] = useState<RoleList | null>(null);
  const [form] = Form.useForm();

  // 切换角色状态
  const handleToggleStatus = async (roleId: number, isActive: boolean) => {
    try {
      setToggleLoading(true);
      await autoLoginInDev();
      
      const request: RoleStatusRequest = {
        is_active: !isActive,
        reason: isActive ? '禁用角色' : '激活角色'
      };
      
      await apiClients.permissions.permissionsRolesToggleStatusCreate({
        id: roleId,
        roleStatusRequest: request
      });
      
      message.success(isActive ? '角色已禁用' : '角色已激活');
      actionRef.current?.reload();
    } catch (error) {
      message.error('状态切换失败');
    } finally {
      setToggleLoading(false);
    }
  };

  // 删除角色
  const handleDelete = async (roleId: number) => {
    try {
      await autoLoginInDev();
      await apiClients.permissions.permissionsRolesDestroy({ id: roleId });
      message.success('角色删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('角色删除失败');
    }
  };

  // 创建角色
  const handleCreate = async (values: RoleRequest) => {
    try {
      await autoLoginInDev();
      await apiClients.permissions.permissionsRolesCreate({ roleRequest: values });
      message.success('角色创建成功');
      setCreateModalVisible(false);
      form.resetFields();
      actionRef.current?.reload();
    } catch (error) {
      message.error('角色创建失败');
    }
  };

  // 更新角色
  const handleUpdate = async (values: RoleRequest) => {
    if (!currentRole) return;
    
    try {
      await autoLoginInDev();
      await apiClients.permissions.permissionsRolesUpdate({
        id: currentRole.id,
        roleRequest: values
      });
      message.success('角色更新成功');
      setEditModalVisible(false);
      setCurrentRole(null);
      form.resetFields();
      actionRef.current?.reload();
    } catch (error) {
      message.error('角色更新失败');
    }
  };

  // 打开编辑模态框
  const handleEdit = (record: RoleList) => {
    setCurrentRole(record);
    form.setFieldsValue({
      name: record.name,
      display_name: record.display_name,
      description: record.description,
      is_active: record.is_active
    });
    setEditModalVisible(true);
  };

  // 表格列定义
  const columns: ProColumns<RoleList>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '角色标识',
      dataIndex: 'name',
      width: 120,
      copyable: true,
    },
    {
      title: '显示名称',
      dataIndex: 'display_name',
      width: 150,
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      search: false,
      render: (_, record) => (
        <Tag color={record.is_active ? 'green' : 'red'}>
          {record.status}
        </Tag>
      ),
    },
    {
      title: '权限数量',
      dataIndex: 'permission_count',
      width: 100,
      search: false,
      render: (count) => (
        <Tag color="blue" icon={<KeyOutlined />}>
          {count}
        </Tag>
      ),
    },
    {
      title: '用户数量',
      dataIndex: 'user_count',
      width: 100,
      search: false,
      render: (count) => (
        <Tag color="purple" icon={<TeamOutlined />}>
          {count}
        </Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: 'created_by_name',
      width: 120,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 180,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Tooltip key="view" title="查看详情">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => history.push(`/permissions/roles/${record.id}`)}
          />
        </Tooltip>,
        <Tooltip key="edit" title="编辑">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            disabled={record.is_system}
            onClick={() => handleEdit(record)}
          />
        </Tooltip>,
        <Tooltip key="toggle" title={record.is_active ? '禁用' : '激活'}>
          <Popconfirm
            title={`确定要${record.is_active ? '禁用' : '激活'}该角色吗？`}
            onConfirm={() => handleToggleStatus(record.id, record.is_active)}
            disabled={record.is_system}
          >
            <Button
              type="link"
              size="small"
              loading={toggleLoading}
              disabled={record.is_system}
              style={{ color: record.is_active ? '#ff4d4f' : '#52c41a' }}
            >
              {record.is_active ? '禁用' : '激活'}
            </Button>
          </Popconfirm>
        </Tooltip>,
        <Tooltip key="delete" title="删除">
          <Popconfirm
            title="确定要删除该角色吗？"
            onConfirm={() => handleDelete(record.id)}
            disabled={record.is_system}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              disabled={record.is_system}
            />
          </Popconfirm>
        </Tooltip>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '角色管理',
        subTitle: '管理系统角色和权限分配',
      }}
    >
      <ProTable<RoleList>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          try {
            await autoLoginInDev();

            const response = await apiClients.permissions.permissionsRolesList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.name || params.display_name,
              isActive: params.is_active,
              isSystem: params.is_system,
            });

            console.log('🚀 角色列表API响应:', response);

            // 🔑 关键：手动提取data字段
            const responseData = (response as any).data || response;
            return {
              data: responseData?.items || [],
              success: true,
              total: responseData?.total || 0,
            };
          } catch (error) {
            message.error('获取角色列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        dateFormatter="string"
        headerTitle="角色列表"
        toolBarRender={() => [
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            新建角色
          </Button>,
        ]}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
      />

      {/* 创建角色模态框 */}
      <Modal
        title="创建角色"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
        >
          <Form.Item
            name="name"
            label="角色标识"
            rules={[
              { required: true, message: '请输入角色标识' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线' }
            ]}
          >
            <Input placeholder="请输入角色标识，如：user_manager" />
          </Form.Item>
          <Form.Item
            name="display_name"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入显示名称，如：用户管理员" />
          </Form.Item>
          <Form.Item
            name="description"
            label="角色描述"
          >
            <Input.TextArea placeholder="请输入角色描述" rows={3} />
          </Form.Item>
          <Form.Item
            name="is_active"
            label="是否激活"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑角色模态框 */}
      <Modal
        title="编辑角色"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setCurrentRole(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdate}
        >
          <Form.Item
            name="name"
            label="角色标识"
            rules={[
              { required: true, message: '请输入角色标识' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线' }
            ]}
          >
            <Input placeholder="请输入角色标识" disabled={currentRole?.is_system} />
          </Form.Item>
          <Form.Item
            name="display_name"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入显示名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="角色描述"
          >
            <Input.TextArea placeholder="请输入角色描述" rows={3} />
          </Form.Item>
          <Form.Item
            name="is_active"
            label="是否激活"
            valuePropName="checked"
          >
            <Switch disabled={currentRole?.is_system} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default RolesPage;
